﻿#define DEBUG_AGENT

using Microsoft.Phone.Scheduler;
using SmarterCharger.App.Infrastructure.Interfaces;
using SmarterCharger.App.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Phone.System.Power;

namespace SmarterCharger.App.Infrastructure
{
    internal class BackgroundAgentStarter : IBackgroundAgentStarter
    {
        private const string PeriodicTaskName = "SmarterCharger.BackgroundAgent";
        private const string PeriodicTaskDescription = "Monitors and stops charging when battery charged according to settings.";
        
        public DateTime ExpirationTime
        {
            get
            {
                return DateTime.Now.AddDays(1);
            }
        }


        public StartBackgrondTaskResult Start()
        {
            try
            {
                var scheduledAction = ScheduledActionService.Find(PeriodicTaskName) as PeriodicTask;
                if (scheduledAction == null)
                    scheduledAction = new PeriodicTask(PeriodicTaskName) { Description = PeriodicTaskDescription };
                else
                    ScheduledActionService.Remove(PeriodicTaskName);

                scheduledAction.ExpirationTime = ExpirationTime;
                ScheduledActionService.Add(scheduledAction);


#if(DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(PeriodicTaskName, TimeSpan.FromSeconds(60));
#endif

                return new StartBackgrondTaskResult { Code = StartBackgrondTaskResultCode.Succeeded };
            }
            catch (InvalidOperationException ex)
            {
                var areBackgroundAgentsDisabled = (ex.Message.Contains("BNS Error: The action is disabled"));
                if (areBackgroundAgentsDisabled)
                    return new StartBackgrondTaskResult { Code = StartBackgrondTaskResultCode.BackgroundAgentsDisabled };

                var isMaxNumber = ex.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
                if (isMaxNumber)
                    return new StartBackgrondTaskResult { Code = StartBackgrondTaskResultCode.MaxNumberOfBackgroundAgentsReached };

                throw;
            }
            catch(SchedulerServiceException)
            {
                return new StartBackgrondTaskResult { Code = StartBackgrondTaskResultCode.FailedToSchedule };
            }
        }


        public StartBackgrondTaskResult Stop()
        {
            var scheduledAction = ScheduledActionService.Find(PeriodicTaskName) as PeriodicTask;
            if (scheduledAction == null)
                ScheduledActionService.Remove(PeriodicTaskName);

            return new StartBackgrondTaskResult { Code = StartBackgrondTaskResultCode.Succeeded };
        }
    }
}
